package com.manger.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BeanUtils {

    public static void copyProperties(Object source, Object target, String[] ignore) throws Exception {
        if (source == null || target == null) {
            return;
        }
        Class<?> sourceClazz = source.getClass();
        Class<?> targetClazz = target.getClass();
        List<Field> sourceFields = new ArrayList<>();
        getFields(sourceClazz, sourceFields);
        List<Field> targetFields = new ArrayList<>();
        getFields(targetClazz, targetFields);
        List<String> ignoreList = Arrays.asList(ignore);
        for (Field sourceField : sourceFields) {
            for (Field targetField : targetFields) {
                if (ignoreList.contains(sourceField.getName())) {
                    continue;
                }
                if (sourceField.getName().equals(targetField.getName())) {
                    targetField.setAccessible(true);
                    sourceField.setAccessible(true);
                    targetField.set(target, sourceField.get(source));
                }
            }
        }
    }

    public static void copyProperties(Object source, Object target) throws Exception {
        copyProperties(source, target, new String[]{});
    }

    private static void getFields(Class<?> clazz, List<Field> fieldList) {
        Field[] fields = clazz.getDeclaredFields();
        while (clazz.getSuperclass() != null) {
            clazz = clazz.getSuperclass();
            getFields(clazz, fieldList);
        }
        fieldList.addAll(Arrays.asList(fields));
    }
}
